package com.sky.handler;

import com.sky.constant.MessageConstant;
import com.sky.exception.BaseException;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    //处理异常
    /**
     * 处理SQL异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public  Result exceptionHandler(SQLIntegrityConstraintViolationException ex){

        // Duplicate entry 'zhangsan' for key 'employee.idx_username'
        //Duplicate entry重复的键值对 即用户名已存在
        String message=ex.getMessage();
        if(message.contains("Duplicate entry")){
            //给前端返回 输入的username已存在的提示信息  动态获取username
            String[] split=message.split(" ");//通过空格将其分隔：Duplicate entry 'zhangsan' for key 'employee.idx_username'
            String username=split[2];//第三个即为username
            String msg=username + MessageConstant.ALREADY_EXISTS;
            return Result.error(msg);

        }else{
            return Result.error(MessageConstant.UNKONWN_ERROR);//后续再改进 有具体的错误时

        }

    }

}
